package com.leetcode.easy;

import com.leetcode.entity.ListNode;

/**
 * @Classname Solution
 * @Description TODO
 * @Date 2020/8/18 15:35
 * @Created by zfl
 * 当l1和l2均为null时，要先判断是否均为null,如果是直接返回Head，如果不是，在初始化l3,原因如下:
 * l3在初始化时，系统自动将l3的val初始化为0，如果不判断l1和l2直接将head = l3,则head就有0的值而非null
 */
public class SolutionMergeTwoListNode {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = null;
        if(l1 != null || l2 != null) {
            ListNode l3 = new ListNode();
            head = l3;
            while (l1 != null || l2 != null) {
                if (l1 != null && l2 != null) {
                    if (l1.val >= l2.val) {
                        l3.val = l2.val;
                        l2 = l2.next;
                    } else {
                        l3.val = l1.val;
                        l1 = l1.next;
                    }
                } else if (l1 == null && l2 != null) {
                    l3.val = l2.val;
                    l3.next = l2.next;
                    return head;
                } else if (l1 != null && l2 == null) {
                    l3.val = l1.val;
                    l3.next = l1.next;
                    return head;
                }
                l3.next = new ListNode();
                l3 = l3.next;
            }
        }
        return head;
    }

    /*
    *@Description 递归、链表，不需要构造新的节点
    *@param l1,l2
    *@return l1
    */
    public ListNode mergeTwoListsTwo(ListNode l1, ListNode l2) {
        if(l1 == null) {
            return l2;
        }
        if(l2 == null) {
            return l1;
        }

        if(l1.val < l2.val) {
            l1.next = mergeTwoListsTwo(l1.next,l2);
            return l1;
        } else {
            l2.next = mergeTwoListsTwo(l1,l2.next);
            return l2;
        }
    }
}
